
(function($){

var
	getForm = function(me){
		return me.find(">form:first");
	},

	getFile = function(me){
		return getForm(me).find(">fieldset>input[type=file]:eq(0)");
	},

	getIFrame = function(me){
		return me.find(">iframe:first");
	},

	fileUploaded = function(e){
		var me = e.data,error = $(this).contents().find("p.error_p").html();
		// mark as uploaded
		me.attr("uploaded", "yes");
		if ( error )
			alert(error);
		// trigger the uploaded custom event.
		me.trigger("uploaded");
		return false;
	};

Core.ObjectTypes["div.uploader"] = function(){

	var me=$(this),
		n_files = me.find(">input[name=n_files]:eq(0)").val(),
		file = getFile(me),
		name = file.attr("name");

	while ( --n_files > 0 ){
		file.after( file.clone().attr("name", name+"_"+n_files) );
	}
	file.attr("name", name+"_0");
	// mark as not yet uploaded
	me.attr("uploaded", "no");
	// set and bind our custom onload
	getIFrame(me).one("load", me, function(e){
										getIFrame(e.data).bind("load", e.data, fileUploaded);
									});
};

$.fn.uploaderUploaded = function(){
	return $(this).attr("uploaded") == "yes";
};

$.fn.uploaderReset = function(){
	$(this).attr("uploaded", "no");
};

})(jQuery);
